package com.chukun.tx.message.queue;

import com.chukun.tx.model.MqMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

public class MessageProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageProcessor.class);

    /**
     * 消息队列
     */
    private BlockingQueue<MqMessage> sendMessageQueue;


    public MessageProcessor(BlockingQueue<MqMessage> sendMessageQueue) {
        this.sendMessageQueue = sendMessageQueue;
    }

    public MessageProcessor () {
        this(new ArrayBlockingQueue<>(1024));
    }


    /**
     * 放入消息
     * @param message
     */
    public synchronized void putMsg(MqMessage message) {
        try {
            Map<Long, MqMessage> messageMap =
                    sendMessageQueue.stream().collect(Collectors.toMap(MqMessage::getMessageId, p -> p));
            if (!messageMap.containsKey(message.getMessageId())) {
                sendMessageQueue.put(message);
            }
        }catch (Exception e) {
            LOGGER.error("MessageProcessor putMsg error",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取消息
     */
    public MqMessage getMsg() {
        try {
            return sendMessageQueue.poll();
        }catch (Exception e) {
            LOGGER.error("MessageProcessor getMsg error",e);
            throw new RuntimeException(e);
        }
    }

}
